package com.jvk.check4home;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.R.drawable;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TabHost;

import com.admob.android.ads.AdView;
import com.jvk.check4home.frwk.frwk;
import com.jvk.check4home.frwk.homeDTO;

public class HomeEdit extends Activity{


	protected static final String PHONE = "phone";
	protected static final String MAIL = "mail";
	protected static final String WEB = "web";
	protected static final String POSI = "posi";
	protected EditText title;
	protected EditText rooms;
	protected EditText bathroom;
	protected EditText floor_number;
	protected EditText scuare_metters;
	protected EditText elevators;
	protected EditText common_places;
	protected EditText parkings;
	protected EditText bus_distance;
	protected EditText metro_distance;
	protected EditText community_pay;
	protected EditText price;
	protected EditText reform_kitchen;
	protected EditText reform_floor;
	protected EditText reform_outside;
	protected EditText reform_doublewin;
	protected EditText reform_furniture;
	protected EditText reform_bath;
	protected EditText reform_rooms;
	protected EditText bathroom_date;
	protected EditText cab_phone;
	protected EditText gas_electricity;
	protected EditText comment;
	protected EditText score;
	protected EditText contact;
	protected EditText website;
	protected EditText phonenumber;
	protected EditText timetocall;
	protected EditText latitude;
	protected EditText longitude;

	protected ImageButton imageSave;
	protected ImageButton imageCancel;

	protected ImageButton buttonCall;
	protected ImageButton buttonMail;
	protected ImageButton buttonMap;
	protected ImageButton buttonWeb;
	
	
	public OnClickListener listenerSave;
	public OnClickListener listenerCancel;

	public OnClickListener listenerCall;
	public OnClickListener listenerMail;
	public OnClickListener listenerMap;
	public OnClickListener listenerWeb;
	
	

	protected homeDTO localHome;
	private homeDTO localHome2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homeedit);
		initXMLElements();
		initListeners();
		AdView add=(AdView) findViewById(R.id.ad);
		add.requestFreshAd();
		if (getIntent().getParcelableExtra("home")!=null)
		{

			Bundle data = getIntent().getExtras();
			localHome = data.getParcelable("home");
			localHome2=new homeDTO(localHome);
			localHome.modify=true;
			setXMLData();
			Log.d("gdata","LOADING ["+localHome.name+"]");
		}else
		{
			localHome=new homeDTO();
			Log.d("gdata","creating!");
		}
	}
	private void setXMLData() {
		Log.d("gdata","setdata["+localHome.r_bathrooms+"] ["+localHome.r_rooms+"]");
		bathroom.setText(localHome.bathrooms);
		bus_distance.setText(localHome.bus_distance);
		timetocall.setText(localHome.call_horary);
		comment.setText(localHome.comments);
		common_places.setText(localHome.commonPlaces);
		community_pay.setText(localHome.community);
		contact.setText(localHome.contact_mail);
		elevators.setText(localHome.elevators);
		floor_number.setText(localHome.flat_number);
		gas_electricity.setText(localHome.gas_electricity);
		latitude.setText(localHome.latit);
		longitude.setText(localHome.longit);
		metro_distance.setText(localHome.metro_distance);
		title.setText(localHome.name);
		parkings.setText(localHome.parkings);
		score.setText(localHome.personal_score);
		phonenumber.setText(localHome.phone);
		cab_phone.setText(localHome.phone_cable);
		price.setText(localHome.price);
		bathroom_date.setText(localHome.r_bathroom_Date);
		reform_bath.setText(localHome.r_bathrooms);
		reform_doublewin.setText(localHome.r_doublewindows);
		reform_floor.setText(localHome.r_floor);
		reform_kitchen.setText(localHome.r_kitchen);
		reform_furniture.setText(localHome.r_muebles);
		reform_outside.setText(localHome.r_outside);
		reform_rooms.setText(localHome.r_rooms);
		rooms.setText(localHome.rooms);
		scuare_metters.setText(localHome.scuareM);
		website.setText(localHome.web);
		

	}
	private void initListeners() {
		listenerSave=new OnClickListener() {

			@Override
			public void onClick(View v) {
				frwk.getInstance(getApplicationContext()).reload=true;
				saveOrCreate();
				

			}
		};
		listenerCancel=new OnClickListener() {

			@Override
			public void onClick(View v) {
				frwk.getInstance(getApplicationContext()).reload=false;
				HomeEdit.this.finish();

			}
		};
		listenerCall=new OnClickListener() {
		
			@Override
			public void onClick(View v) {
				if (isValid(phonenumber.getText().toString(),PHONE)) 
				{
				try {
				        Intent callIntent = new Intent(Intent.ACTION_CALL);
				        callIntent.setData(Uri.parse("tel:"+phonenumber.getText().toString()));
				        startActivity(callIntent);
				    } catch (ActivityNotFoundException e) {
				        Log.e("helloandroid dialing example", "Call failed", e);
				    }
				}else
				{
					AlertDialog.Builder builder3 = new AlertDialog.Builder(HomeEdit.this);
					builder3.setMessage(getApplicationContext().getString(R.string.err_phone)+"[err:wtf?]")
					.setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
					AlertDialog alert3 = builder3.create();
					alert3.show();
				}
			}

		};
		listenerMail=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isValid(contact.getText().toString(),MAIL)) 
				{
				try {
					Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
                    emailIntent.setType("plain/text");
                    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ contact.getText().toString()});
                    emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getApplicationContext().getString(R.string.subject));
                    startActivity(Intent.createChooser(emailIntent, ""));
				    } catch (ActivityNotFoundException e) {
				        Log.e("helloandroid dialing example", "Call failed", e);
				    }
				}else
				{
					AlertDialog.Builder builder3 = new AlertDialog.Builder(HomeEdit.this);
					builder3.setMessage(getApplicationContext().getString(R.string.err_mail)+"[err:wtf?]")
					.setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
					AlertDialog alert3 = builder3.create();
					alert3.show();
				}
				
			}
		};
		listenerMap=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String posi=latitude.getText().toString()+","+longitude.getText().toString();
				if (isValid(posi,POSI)) 
				{
				try {
					Log.d("gdata","posi["+posi+"]");
					Intent myIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("geo:"+createMapFrom(posi)));
				        startActivity(myIntent);
				    } catch (ActivityNotFoundException e) {
				        Log.e("helloandroid dialing example", "Call failed", e);
				    }
				}else
				{
					AlertDialog.Builder builder3 = new AlertDialog.Builder(HomeEdit.this);
					builder3.setMessage(getApplicationContext().getString(R.string.err_locat)+"[err:wtf?]")
					.setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
					AlertDialog alert3 = builder3.create();
					alert3.show();
				}
				
			}


		};
		listenerWeb=new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isValid(website.getText().toString(),WEB)) 
				{
				try {
					Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(website.getText().toString()));
				        startActivity(myIntent);
				    } catch (ActivityNotFoundException e) {
				        Log.e("helloandroid dialing example", "Call failed", e);
				    }
				}else
				{
					AlertDialog.Builder builder3 = new AlertDialog.Builder(HomeEdit.this);
					builder3.setMessage(getApplicationContext().getString(R.string.err_website)+"[err:wtf?]")
					.setCancelable(false)
					.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.dismiss();
						}
					});
					AlertDialog alert3 = builder3.create();
					alert3.show();
				}
				
			}
		};
		imageSave.setOnClickListener(listenerSave);
		imageCancel.setOnClickListener(listenerCancel);	
		buttonCall.setOnClickListener(listenerCall);
		buttonWeb.setOnClickListener(listenerWeb);
		buttonMap.setOnClickListener(listenerMap);
		buttonMail.setOnClickListener(listenerMail);
	}

	public boolean isNum(String s) {
		try {
		Float.parseFloat(s);
		}
		catch (NumberFormatException nfe) {
		return false;
		}
		return true;
		}
	
	   public boolean validateEmail(String email) {
		   
	       Pattern p = Pattern.compile("[a-zA-Z0-9]+[.[a-zA-Z0-9_-]+]*@[a-z0-9][\\w\\.-]*[a-z0-9]\\.[a-z][a-z\\.]*[a-z]$");//me gusta esta
	 
	       Matcher m = p.matcher(email);
	       return m.matches();
	   }

	
	public boolean isValid(String string, String phone) {
		if (phone.equals(PHONE))
		{
			if ((string.length()>8)&&(isNum(string)))
			{
				return true;
			}else
			{
				return false;
			}
		}
		else if (phone.equals(MAIL))
		{
			if (string.length()>0)
			{
				return validateEmail(string);
			}else
			{
				return false;
			}
		}
		else if (phone.equals(WEB))
		{
			return (string.length()>0);
		}
		else if (phone.equals(POSI))
		{
			return (string.length()>0);
				
		}
		return true;
	}
	private String createMapFrom(String posi) {
		/*
		 * geo:latitude,longitude
geo:latitude,longitude?z=zoom
geo:0,0?q=my+street+address
geo:0,0?q=business+near+city
		 * */
		String fts[]=posi.split(",");
		if (fts.length>0)//es del tipo latitud longitud
		{
			try {
			Float d=Float.valueOf(posi);
			return posi;
			}catch (Exception e) {
				return "0,0?q="+posi.replace(' ', '+');
			}
		}else
		{
			return "0,0?q="+posi.replace(' ', '+');
		}
	}
	
	
	protected void saveOrCreate() {
		if (testAllField())
		{
			localHome.bathrooms=bathroom.getText().toString();
			localHome.bus_distance=bus_distance.getText().toString();
			localHome.call_horary=timetocall.getText().toString();
			localHome.comments=comment.getText().toString();
			localHome.commonPlaces=common_places.getText().toString();
			localHome.community=community_pay.getText().toString();
			localHome.contact_mail=contact.getText().toString();
			localHome.elevators=elevators.getText().toString();
			localHome.flat_number=floor_number.getText().toString();
			localHome.gas_electricity=gas_electricity.getText().toString();
			localHome.latit=latitude.getText().toString();
			localHome.longit=longitude.getText().toString();
			localHome.metro_distance=metro_distance.getText().toString();
			localHome.name=title.getText().toString();
			localHome.parkings=parkings.getText().toString();
			localHome.personal_score=score.getText().toString();
			localHome.phone=phonenumber.getText().toString();
			localHome.phone_cable=cab_phone.getText().toString();
			localHome.price=price.getText().toString();
			localHome.r_bathroom_Date=bathroom_date.getText().toString();
			localHome.r_bathrooms=reform_bath.getText().toString();
			localHome.r_doublewindows=reform_doublewin.getText().toString();
			localHome.r_floor=reform_floor.getText().toString();
			localHome.r_kitchen=reform_kitchen.getText().toString();
			localHome.r_muebles=reform_furniture.getText().toString();
			localHome.r_outside=reform_outside.getText().toString();
			localHome.r_rooms=reform_rooms.getText().toString();
			localHome.rooms=rooms.getText().toString();
			localHome.scuareM=scuare_metters.getText().toString();
			localHome.web=website.getText().toString();
			if (getIntent().getParcelableExtra("home")!=null)
			{
				frwk.getInstance(getApplicationContext()).updateNewhome(localHome2,localHome);
			}else
			{
				frwk.getInstance(getApplicationContext()).addNewhome(localHome);
			}
			HomeEdit.this.finish();
			
		}else
		{
			AlertDialog.Builder builder = new AlertDialog.Builder(HomeEdit.this);
			builder.setMessage(getApplicationContext().getString(R.string.dial_fillall))
			       .setCancelable(false)
			       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			               dialog.dismiss();
			           }
			       });
			AlertDialog alert = builder.create();
			alert.show();
		}

	}
	private boolean testAllField() {
		if (bathroom.getText().toString().length()<1)return false;
		if (bus_distance.getText().toString().length()<1)return false;
		if (timetocall.getText().toString().length()<1)return false;
		if (comment.getText().toString().length()<1)return false;
		if (common_places.getText().toString().length()<1)return false;
		if (community_pay.getText().toString().length()<1)return false;
		if (contact.getText().toString().length()<1)return false;
		if (elevators.getText().toString().length()<1)return false;
		if (floor_number.getText().toString().length()<1)return false;
		if (gas_electricity.getText().toString().length()<1)return false;
		if (latitude.getText().toString().length()<1)return false;
		if (longitude.getText().toString().length()<1)return false;
		if (metro_distance.getText().toString().length()<1)return false;
		if (title.getText().toString().length()<1)return false;
		if (parkings.getText().toString().length()<1)return false;
		if (score.getText().toString().length()<1)return false;
		if (phonenumber.getText().toString().length()<1)return false;
		if (cab_phone.getText().toString().length()<1)return false;
		if (price.getText().toString().length()<1)return false;
		if (bathroom_date.getText().toString().length()<1)return false;
		if (reform_bath.getText().toString().length()<1)return false;
		if (reform_doublewin.getText().toString().length()<1)return false;
		if (reform_floor.getText().toString().length()<1)return false;
		if (reform_kitchen.getText().toString().length()<1)return false;
		if (reform_furniture.getText().toString().length()<1)return false;
		if (reform_outside.getText().toString().length()<1)return false;
		if (reform_rooms.getText().toString().length()<1)return false;
		if (rooms.getText().toString().length()<1)return false;
		if (scuare_metters.getText().toString().length()<1)return false;
		if (website.getText().toString().length()<1)return false;
		return true;
	}
	private void initXMLElements() {
		TabHost tabs = (TabHost)this.findViewById(R.id.tabs);
		tabs.setup();
		tabs.addTab(tabs.newTabSpec(getApplicationContext().getString(R.string.e_common))
				.setContent(R.id.edit_la_common)
				.setIndicator(getApplicationContext().getString(R.string.e_common)));
		tabs.addTab(tabs.newTabSpec(getApplicationContext().getString(R.string.e_reforms))
				.setContent(R.id.edit_la_reforms)
				.setIndicator(getApplicationContext().getString(R.string.e_reforms)));
		tabs.addTab(tabs.newTabSpec(getApplicationContext().getString(R.string.e_contact))
				.setContent(R.id.edit_la_contact)
				.setIndicator(getApplicationContext().getString(R.string.e_contact)));
		buttonCall=(ImageButton) findViewById(R.id.edit_btn_call);
		buttonCall.setImageResource(drawable.sym_action_call);
		buttonMail=(ImageButton) findViewById(R.id.edit_btn_mail);
		buttonMail.setImageResource(drawable.ic_menu_send);
		buttonMap=(ImageButton) findViewById(R.id.edit_btn_map);
		buttonMap.setImageResource(drawable.ic_menu_mylocation);
		buttonWeb=(ImageButton) findViewById(R.id.edit_btn_web);
		buttonWeb.setImageResource(drawable.ic_menu_info_details);
		title=(EditText)findViewById(R.id.edit_txt_title2);
		rooms=(EditText)findViewById(R.id.edit_txt_rooms);
		bathroom=(EditText)findViewById(R.id.edit_txt_bathrooms);
		floor_number=(EditText)findViewById(R.id.edit_txt_flat);
		scuare_metters=(EditText)findViewById(R.id.edit_txt_scuarem);
		elevators=(EditText)findViewById(R.id.edit_txt_elevators);
		common_places=(EditText)findViewById(R.id.edit_txt_commonplaces);
		parkings=(EditText)findViewById(R.id.edit_txt_parkings);
		bus_distance=(EditText)findViewById(R.id.edit_txt_bus_distance);
		metro_distance=(EditText)findViewById(R.id.edit_txt_metro_distance);
		community_pay=(EditText)findViewById(R.id.edit_txt_comm_tax);
		price=(EditText)findViewById(R.id.edit_txt_price);
		reform_kitchen=(EditText)findViewById(R.id.edit_txt_kitchen);
		reform_floor=(EditText)findViewById(R.id.edit_txt_floor);
		reform_outside=(EditText)findViewById(R.id.edit_txt_outside);
		reform_doublewin=(EditText)findViewById(R.id.edit_txt_doublewin);
		reform_furniture=(EditText)findViewById(R.id.edit_txt_ikea);
		reform_bath=(EditText)findViewById(R.id.edit_txt_ref_bath);
		reform_rooms=(EditText)findViewById(R.id.edit_txt_ref_rooms);
		bathroom_date=(EditText)findViewById(R.id.edit_txt_datebath);
		cab_phone=(EditText)findViewById(R.id.edit_txt_caborphone);
		gas_electricity=(EditText)findViewById(R.id.edit_txt_gas_or_elec);
		comment=(EditText)findViewById(R.id.edit_txt_comment);
		score=(EditText)findViewById(R.id.edit_txt_rating);
		contact=(EditText)findViewById(R.id.edit_txt_contact);
		website=(EditText)findViewById(R.id.edit_txt_website);
		phonenumber=(EditText)findViewById(R.id.edit_txt_phone_num);
		timetocall=(EditText)findViewById(R.id.edit_txt_phonetime);
		latitude=(EditText)findViewById(R.id.edit_txt_latitude);
		longitude=(EditText)findViewById(R.id.edit_txt_longitude);
		imageCancel=(ImageButton)findViewById(R.id.edit_btn_delete);		
		imageSave=(ImageButton)findViewById(R.id.edit_btn_save);		
	}

}
